package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.query.RegionQuery;
import cn.wolfcode.wolf2w.repository.RegionRepository;
import cn.wolfcode.wolf2w.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RegionServiceImpl implements IRegionService {
    @Autowired
    private RegionRepository regionRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Region region) {
        regionRepository.save(region);
    }

    @Override
    public void update(Region region) {
        regionRepository.save(region);
    }

    @Override
    public void delete(String id) {
        regionRepository.deleteById(id);
    }

    @Override
    public Region get(String id) {
        return regionRepository.findById(id).orElse(null);
    }

    @Override
    public List<Region> listAll() {
        return regionRepository.findAll();
    }

    @Override
    public Page<Region> query(RegionQuery qo) {
        // PageResult （2传2查3计算） total list
        // 条件连接对象
        Query query = new Query();
        // total（参数：query，从哪张表/集合查）
        long total = mongoTemplate.count(query, Region.class);
        if (total == 0){
            return Page.empty();   // 空分页
        }
        // list + 分页pageable
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        query.with(pageable);
        List<Region> list = mongoTemplate.find(query, Region.class);

        return new PageImpl<>(list,pageable,total);   // list  pageable  total
    }

    @Override
    public void changeHotValue(int hot, String id) {
        // 方法1：查 改 保存
     /*   // 1、根据id找这条数据
        Region region = regionRepository.findById(id).orElse(null);
        // 2、更改状态（设置热门 和 取消热门）
        region.setIshot(hot);
        // 3、保存到数据库
        regionRepository.save(region);
        // 或者
       // this.update(region);*/

        // 方法2：updateMany
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.set("ishot",hot);
        mongoTemplate.updateMulti(query,update,Region.class);
    }

    @Override
    public List<Region> getHotRegion() {
        return regionRepository.findByIshotOrderBySequenceAsc(Region.STATE_HOT);
    }
}
